<template>
  <view class="page">
    <uni-nav-bar
      background-color="#00a9ff"
      title="咨询对话"
      color="white"
      :fixed="true"
      statusBar="true"
      left-icon="left"
      @clickLeft="back"
    />
    <view class="chat">
      <scroll-view
        ref="scrollview"
        :style="{ height: `${windowHeight}rpx` }"
        id="scrollview"
        scroll-y="true"
        class="scroll-view"
      >
        <view id="msglistview" class="chat-body">
          <!-- 后续消息根据数组动态渲染 -->
          <view v-for="(item, index) in msgList" :key="index">
            <view class="item self" v-if="item.role === 'user'">
              <view class="content right">{{ item.content }}</view>
              <image src="../../static/icons/用户on.png" class="avatar"></image>
            </view>
            <view class="item Ai" v-if="item.role === 'bot'">
              <image src="../../static/logo.png" class="avatar"></image>
              <view class="content left">{{ item.content }}</view>
            </view>
          </view>
        </view>
      </scroll-view>

      <view class="chat-bottom">
        <view class="send-msg">
          <view class="uni-textarea">
            <textarea v-model="chatMsg" maxlength="-1" :show-confirm-bar="false" auto-height></textarea>
          </view>
          <button @click="handleSend" class="send-btn">发送</button>
        </view>
      </view>
    </view>
  </view>
</template>


<script>
import { sendMessage } from '../../utils/openai';

export default {
  data() {
    return {
	  chatTime:'',
      scrollTop: 0,
      chatMsg: '',
      msgList: [
        // 初始化对话历史
        {
          botContent: '你好，请问我有什么可以帮助你的吗？',
          recordId: 0,
          titleId: 0,
          userContent: '你好！',
          userId: 0
        }
      ]
    };
  },
  computed: {
    windowHeight() {
      return this.rpxTopx(uni.getSystemInfoSync().windowHeight - 130);
    }
  },
  onLoad(res) {
  	this.chatTime = res.chattime;
  },
  onUnload() {
  	uni.setStorageSync('chat'+this.chatTime,this.msgList)
  },
  methods: {


	onload(){
		uni.hideTabBar();
	},

	onload(){
		uni.hideTabBar();
	},

    // 返回方法
    back() {
      uni.navigateBack();
    },
    // rpx转px方法
    rpxTopx(px) {
      let deviceWidth = wx.getSystemInfoSync().windowWidth;
      let rpx = (750 / deviceWidth) * Number(px);
      return Math.floor(rpx);
    },
    // 发送消息方法

    async handleSend() {
      if (!this.chatMsg || /^\s*$/.test(this.chatMsg)) {
        uni.showToast({
          title: '不能发送空白消息',
          icon: 'none'
        });
        return;
      }
    
      const userMessage = {
        content: this.chatMsg,
        role: "user"
      };
      this.msgList.push(userMessage);
      this.chatMsg = '';
    
      this.$nextTick(() => {
        this.scrollTop = this.$refs.scrollview.scrollHeight;
      });
     try {
        const response = await sendMessage(this.msgList);
        console.log('Response from API:', response);
    
     if (response && response.choices && response.choices.length > 0) {
       const botMessage = {
         content: response.choices[0].message.content, 
         role: "bot"
       };
       this.msgList.push(botMessage);
     
       this.$nextTick(() => {
         this.scrollTop = this.$refs.scrollview.scrollHeight;
       });
     } else {
       throw new Error('Invalid response format');
     }

      } catch (error) {
        console.error('Error sending message:', error);
        uni.showToast({
          title: '消息发送失败',
          icon: 'none'
        });
      }
    },

    async handleSend() {
      if (!this.chatMsg || /^\s*$/.test(this.chatMsg)) {
        uni.showToast({
          title: '不能发送空白消息',
          icon: 'none'
        });
        return;
      }
    
      const userMessage = {
        content: this.chatMsg,
        role: "user"
      };
      this.msgList.push(userMessage);
      this.chatMsg = '';
    
      this.$nextTick(() => {
        this.scrollTop = this.$refs.scrollview.scrollHeight;
      });
     try {
        const response = await sendMessage(this.msgList);
        console.log('Response from API:', response);
    
     if (response && response.choices && response.choices.length > 0) {
       const botMessage = {
         content: response.choices[0].message.content, 
         role: "bot"
       };
       this.msgList.push(botMessage);
     
       this.$nextTick(() => {
         this.scrollTop = this.$refs.scrollview.scrollHeight;
       });
     } else {
       throw new Error('Invalid response format');
     }

      } catch (error) {
        console.error('Error sending message:', error);
        uni.showToast({
          title: '消息发送失败',
          icon: 'none'
        });
      }
    }


  },
  mounted() {
    // 组件挂载后滚动到底部
    this.$nextTick(() => {
      this.scrollTop = this.$refs.scrollview.scrollHeight;
    });
  }
};
</script>


<style lang="scss" scoped>
$chatContentbgc: #c2dcff;
$sendBtnbgc: #4f7df5;

view,
button,
text,
input,
textarea {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.chat {
  display: flex;
  flex-direction: column;
  .scroll-view {
    ::-webkit-scrollbar {
      display: none;
      width: 0 !important;
      height: 0 !important;
      -webkit-appearance: none;
      background: transparent;
      color: transparent;
    }
    .chat-body {
      display: flex;
      flex-direction: column;
      padding: 0 20rpx;

      .self {
        justify-content: flex-end;
      }
      .item {
        display: flex;
        padding: 23rpx 30rpx;

        .right {
          background-color: $chatContentbgc;
        }
        .left {
          background-color: #fff;
        }
        .right::after {
          position: absolute;
          display: inline-block;
          content: '';
          width: 0;
          height: 0;
          left: 100%;
          top: 10px;
          border: 12rpx solid transparent;
          border-left: 12rpx solid $chatContentbgc;
        }

        .left::after {
          position: absolute;
          display: inline-block;
          content: '';
          width: 0;
          height: 0;
          top: 10px;
          right: 100%;
          border: 12rpx solid transparent;
          border-right: 12rpx solid #ffffff;
        }

        .content {
          position: relative;
          max-width: 486rpx;
          border-radius: 8rpx;
          word-wrap: break-word;
          padding: 24rpx 24rpx;
          margin: 0 24rpx;
          border-radius: 5px;
          font-size: 32rpx;
          font-family: PingFang SC;
          font-weight: 500;
          color: #333333;
          line-height: 42rpx;
        }

        .avatar {
          width: 78rpx;
          height: 78rpx;
          border-radius: 100%;
        }
      }
    }
  }
  .chat-bottom {
    width: 100%;
    height: auto;
    background-color: #ddf9ff;

    .send-msg {
      display: flex;
      align-items: flex-end;
      padding: 20rpx 30rpx;
      width: 100%;
      height: auto;
      position: fixed;
      bottom: 0;
      background: #ededed;
    }

    .uni-textarea {
      textarea {
        width: 537rpx;
        background: #ffffff;
        border-radius: 8rpx;
        font-size: 32rpx;
        color: #333333;
        padding: 15rpx;
        margin-bottom: 20rpx;
      }
    }

    .send-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: 25rpx;
      width: 128rpx;
      height: 70rpx;
      background: $sendBtnbgc;
      border-radius: 8rpx;
      font-size: 28rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: #ffffff;
      line-height: 28rpx;
      margin-bottom: 20rpx;
    }
  }
}
</style>
